<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/4/3
 * Time: 14:05
 * 订单
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Base;
use app\common\model\BatchOrder;
use app\common\model\CapitalLog;
use app\common\model\FundsRecord;
use app\common\model\GoodsRebate;
use app\common\model\GoodsSpike;
use app\common\model\OrderRemind;
use app\common\model\Payconfig;
use app\common\model\ReimburseAmount;
use app\common\model\ReimburseRecord;
use app\common\model\SupplyChain;
use app\common\model\UserAgent;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Log;
use think\Request;

class Order extends Api {


    protected static $dir;

	protected $inputs;
	protected $noNeedRight = ['*'];
	protected $noNeedLogin = ['notifyalipay', 'notifywechatapp', 'handwxpay'];

	public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$dir = RUNTIME_PATH.$this->request->controller().DS.$this->request->action().DS;
        $this->inputs = $this->request->input();
    }


    /**
     * 写日志
     * @param string $msg 参数
     * @param string $dir 参数
     */
    public static function logWrite($msg,$dir='')
    {
        if ($dir)
        {
            Log::init(['path'=>$dir]);
        }
        Log::write($msg);
        Log::init(['path'=>LOG_PATH]);
    }

    /**
	 * 确认订单
	 */
	public function confirmOrder(){

		//结算类型 cart从购物车，goods商品详情立即购买
		$type = input('post.type');
		if(!$type) {
			$this->error('请选择结算类型');
		}
		
		//收货地址ID,不传使用默认地址
		$addressId = input('post.address_id','','int');
		
		//立即购买的商品ID
		$goodsId = input('post.goods_id');
		
		//立即购买的数量
		$number = input('post.number');
		
		//立即购买时的商品规格ID
		$priceId = input('post.price_id');
		
		//购物车结算的购物车ID
		$cartIds = input('post.cart_ids');
		
		$model = new \app\common\model\Order();
		
		$userId = $this->auth->id;
		
		$activeType = input('post.active_type');
		if($activeType == 'spike') {
			$spikeModel = new GoodsSpike();
			$goods = $spikeModel->getGoods($goodsId, $number, $priceId, $userId);
			if(!$goods){
				$this->error($spikeModel->getError());
			}
		} else {
			$goods = $model->getGoods($type, $cartIds, $goodsId, $number, $priceId);
			if(!$goods){
				$this->error($model->getError());
			}
		}
		
		
		$addressWhere = [
			'ad.user_id' => $userId,
			'ad.status' => 1,
		];
		if($addressId){
			$addressWhere['ad.id'] = $addressId;
		}
		$address = Db::name('address')->alias('ad')
			->join('area p','p.id = ad.province_id','left')
			->join('area c','c.id = ad.city_id','left')
			->join('area a','a.id = ad.area_id','left')
			->where($addressWhere)
			->order(['ad.is_default' => 'DESC'])
			->field('ad.id, ad.recipients,ad.mobile,ad.address, ad.is_default,p.areaname as province, c.areaname as city, a.areaname as area, ad.province_id')
			->find();
		
		
		//计算价格
		$data = $model->calculationOrder($userId, $goods,1,$address);
		if(!$data) {
			$this->error($model->getError());
		}
		if($address) {
			$data['address'] = $address;
		} else {
			$data['address'] = [
				'id'=>'',
				'recipients'=>'',
				'mobile'=>'',
				'address'=>'',
				'is_default'=>'',
				'province' => '',
				'city' => '',
				'area' => '',
				'province_id' => ''
			];
		}
		$data['user_point'] = $this->auth->integral;
		$this->success('计算成功', $data);
	}
	
	/**
	 * 创建订单
	 */
	public function createOrder(){
		//结算类型 cart从购物车，goods商品详情立即购买
		$type = input('post.type');
		
		//收货地址ID,不传使用默认地址
		$addressId = input('post.address_id','','int');
		if(!$addressId){
			$this->error('请选择收货地址');
		}
		
		//立即购买的商品ID
		$goodsId = input('post.goods_id');
		
		//立即购买的数量
		$number = input('post.number');
		
		//立即购买时的商品规格ID
		$priceId = input('post.price_id');
		
		//购物车结算的购物车ID
		$cartIds = input('post.cart_ids');
		
		
		$userId = $this->auth->id;
		$addressWhere = [
			'ad.user_id' => $userId,
			'ad.status' => 1,
			'ad.id' => $addressId
		];
		$address = Db::name('address')->alias('ad')
			->join('area p','p.id = ad.province_id','left')
			->join('area c','c.id = ad.city_id','left')
			->join('area a','a.id = ad.area_id','left')
			->where($addressWhere)
			->field('ad.id, ad.recipients,ad.mobile,ad.address, p.areaname as province, c.areaname as city, a.areaname as area, ad.province_id, ad.city_id, ad.area_id')
			->find();
		if(!$address){
			$this->error('收货地址不存在');
		}
		
		$model = new \app\common\model\Order();
		
		$activeType = input('post.active_type');
		if($activeType == 'spike') {
			$spikeModel = new GoodsSpike();
			$goods = $spikeModel->getGoods($goodsId, $number, $priceId, $userId);
			if(!$goods){
				$this->error($spikeModel->getError());
			}
		} else {
			$goods = $model->getGoods($type, $cartIds, $goodsId, $number, $priceId);
			if(!$goods){
				$this->error('获取商品信息出错'.$model->getError());
			}
		}
		
		
		//订单留言，单商家时直接传输，多商家时格式为：商家1ID=商家1留言&商家2ID=商家2留言。。。
		$msg = input('post.message');
		$message = [];
		if($msg){
			if($type == 'cart') {
				$message = explode('&',$msg);
				$new = [];
				foreach ($message as $v){
					$arr = explode('=',$v);
					$new[$arr[0]] = $arr[1];
				}
				$message = $new;
			} else {
				$message[$goods[0]['business_id']] = $msg;
			}
			
		}
		
		
		//生成订单
		$res = $model->calculationOrder($userId, $goods,0,$address,$message);
		
		if(!$res){
			$this->error($model->getError());
		} else {
			$cartModel = new \app\common\model\Cart();
			if($type == 'cart'){
				Db::name('cart')->where(['id' => ['in', $cartIds]])->update(['status'=>$cartModel::STATUS_BUY]);
			}
			$this->success('添加订单成功', $res);
		}
		
	}
	
	
	/**
	 * 订单列表
	 */
	public function index(){
		$userId = $this->auth->id;
		$where['o.user_id'] = $userId;
		
		$status = input('post.status');
		$status && $where['o.order_status'] = $status;
		
		$model = new \app\common\model\Order();
		if($status && $status==$model::STATUS_SIGN){
			$where['o.comment_status'] = 0;
		}
		
		//显示没删除的订单
		$where['o.deleted'] = $model::USER_DELETE_N;
		
		$page = input('post.page',1, 'int');
		
		$orders = $model->orderList($where, $page);
		$this->success('查询成功', array_values($orders));
	}
	
	
	/**
	 * 订单详情
	 */
	public function detail(){
		$id = input('post.order_id');
		if(!$id){
			$this->error('请选择要查询的订单');
		}
		
		$model = new \app\common\model\Order();
		$detail = $model->orderDetail($this->auth->id, $id);
		if($detail){
			$this->success('查询成功', $detail);
		} else {
			$this->error($model->getError());
		}
	}
	
	/**
	 * 支付订单
	 */
	public function payOrder(){
        $user = $this->auth->getUser();
        
        $orderId = input('post.order_id');
        $paymentId = input('post.payment_id');
        $payPassword = input('post.pay_password');
        
        if (!$paymentId || !$orderId) {
            $this->error('参数错误');
        }
        
        //订单ID形成数组
        $ids = explode(',', $orderId);
        
        $orderModel = new \app\common\model\Order();
        
        $orders = $orderModel->where(['id' => ['in', $ids], 'user_id' => $user['id'], 'order_status' => $orderModel::STATUS_WAIT_PAYMENT])->select();
        if(!$orders) {
        	$this->error('没有需要支付的订单');
        }
        
        $paymentModel = new \app\common\model\Payment();
        //查找支付方式
        $payment = $paymentModel->where([
        	'status' => $paymentModel::STATUS_Y,
	        'id' => $paymentId,
        ])->find();
        !$payment && $this->error('支付方式错误');
        
        //如果支付方式需要支付密码，判断支付密码是否正确
        if($payment['need_password'] == $paymentModel::PASSWORD_Y){
        	!$payPassword && $this->error('请输入支付密码');
        	
            if($user['pay_password'] != $this->auth->getEncryptPassword($payPassword, $user['salt'])) {
	            $this->error('支付密码错误');
            }
        }
        
        //计算订单总价格
		$totalAmount = 0;
  
        
        switch ($payment['pay_type']) {
			//余额支付
	        case $paymentModel::PAY_TYPE_BALANCE:
		        if ($totalAmount > $user['balance']) {
			        $this->error('余额不足');
		        }
		
		        $res = $paymentModel->balancePayOrder($orders, $user, $orderId);
		        if($res) {
			        $this->success('支付成功');
		        } else {
			        $this->error($paymentModel->getError());
		        }
		        break;
	
	        //积分支付
	        case $paymentModel::PAY_TYPE_POINT:
		        if ($totalAmount > $user['integral']) {
			        $this->error('积分不足');
		        }
		
		        $res = $paymentModel->integralPayOrder($orders, $user, $orderId);
		        if($res) {
			        $this->success('支付成功');
		        } else {
			        $this->error($paymentModel->getError());
		        }
		        break;
	        case $paymentModel::PAY_TYPE_ALI:
            	
            	//支付宝支付
				$batchModel = new BatchOrder();
				
            	//生成统一支付订单
				$batchNo = $batchModel->createRecord($user['id'], $orderId, $totalAmount);
				if(!$batchNo) {
					$this->error('生成支付订单出错');
				}
				
            	//支付宝支付
                $returnArr['orderid'] = $batchNo;
                $returnArr['callback'] = $this->request->domain() . url('api/order/notifyAliPay','','');
                $returnArr['acctId'] = $payment['appid'];
                $returnArr['sellerId'] = $payment['appid'];
                $returnArr['privatekey'] = $payment['private_key'];
                $returnArr['keyWord'] = 'pay_order';
                $returnArr['amount'] = $totalAmount;

                $this->success("OK",$returnArr);
                break;
	        case $paymentModel::PAY_TYPE_WEIXIN:
	            //微信支付
	            $batchModel = new BatchOrder();
	
	            //生成统一支付订单
	            $batchNo = $batchModel->createRecord($user['id'], $orderId, $totalAmount);
	            if(!$batchNo) {
		            $this->error('生成支付订单出错');
	            }
	            
            	//微信支付
                $config = [
                    'appid' => $payment['appid'],
                    'mch_id' => $payment['mch_id'],
                    'mch_key' => $payment['private_key'],
                ];

                $wxPay = load_wec("Pay",$config);
                $callback = $this->request->domain() . url('api/order/notifyWeChatApp','','');
                $data = [
                    "body"              => 'Pay',
                    "out_trade_no"      => (string)$batchNo,
                    'attach'            => 'payorder', //附加数据(非必填)
                    "total_fee"         => $totalAmount*100,
                    "notify_url"        => $callback,
                    "trade_type"        => 'APP',
                    "fee_type"          => 'CNY',
                    "spbill_create_ip"  => $this->request->ip()
                ];

                $res = $wxPay->createOrder($data);
                $prepay_id = $res['prepay_id'];
                $result = $wxPay->createMchPay($prepay_id);
                $returnArr = [
                    'keyWord' => 'pay_order',
                    'acctId' => $payment['mch_id'],
                    'orderid' => $batchNo,
                    'callback' => $callback,
                    "sign" => $result['paySign'],
                    "sellerId" => $payment['mch_id'],
                    "prepay_id" => $prepay_id,
                    "appid" => $payment['appid'],
                    "nonce_str" => $result['nonceStr'],
                    "trade_type" => "APP",
                    "amount" => $totalAmount*100,
                    "privateKey" => $payment['private_key']
                ];
                $this->success("OK",$returnArr);
                break;
            default:
                $this->error('支付方式错误');
        }
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrder(){
		$id = input('post.id');
		if(!$id){
			$this->error('参数错误');
		}
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$where = [
			'id' => $id,
			'user_id' => $userId
		];
		$row = $model->where($where)->find();
		if(!$row){
			$this->error('订单不存在');
		}
		
		if($row['order_status'] != $model::STATUS_WAIT_PAYMENT){
			$this->error('该订单不可取消');
		}
		
		$res = $row->save(['order_status' => $model::STATUS_CLOSE, 'close_type' => $model::CLOSE_TYPE_USER]);
		if(!$res){
			$this->error('取消订单出错，请稍候重试');
		} else {
			$this->success('取消订单成功');
		}
	}
	
	/**
	 * 删除订单
	 */
	public function delOrder(){
		$id = input('post.id');
		if(!$id){
			$this->error('参数错误');
		}
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$where = [
			'id' => $id,
			'user_id' => $userId
		];
		$row = $model->where($where)->find();
		if(!$row){
			$this->error('订单不存在');
		}
		
		//关闭或成功的订单才可删除
		if($row['order_status'] != $model::STATUS_CLOSE && $row['order_status'] != $model::STATUS_SIGN){
			$this->error('该订单不可删除');
		}
		
		$res = $row->save(['deleted' => $model::USER_DELETE_Y]);
		if(!$res){
			$this->error('删除订单出错，请稍候重试');
		} else {
			$this->success('删除订单成功');
		}
	}
	

	/**
	 * 确认收货
	 */
	public function signOrder(){
		$orderId = input('post.order_id');
		if(!$orderId){
			$this->error('参数错误');
		}
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$where = [
			'id' => $orderId,
			'user_id' => $userId
		];
		$row = $model->where($where)->find();
		if(!$row){
			$this->error('订单不存在');
		}
		
		if($row['order_status'] != $model::STATUS_WAIT_SIGN){
			$this->error('非待签收订单');
		}
		
		Db::startTrans();
		try {
			
			//签收订单
			$res = $model->sign($orderId, $userId);
			if(!$res) {
				throw new Exception($model->getError());
			}
			
			Db::commit();
			$this->success('订单签收成功');
			
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
	
	
	/**
	 * 评价
	 */
	public function comment(){
		$userId = $this->auth->id;
		$orderId = input('post.order_id');
		$service_score = input('post.service_score', 5, 'int');
		$shipping_score = input('post.shipping_score', 5, 'int');
		
		$data = input('post.');
		$goods = $data['goods'];
		if(!$orderId || !$goods) {
			$this->error('参数错误');
		}
		
		$model = new \app\common\model\Order();
		$order = $model->where(['user_id' => $userId, 'id' => $orderId])->find();
		!$order && $this->error('订单不存在');
		
		if($order['comment_status'] != 0) {
			$this->error('该订单已评价');
		}
		
		$comments = [];
		foreach($goods as $k => $v) {
			if($v['score'] <0 ) {
				$v['score'] = 0;
			} else if($v['score'] > 5) {
				$v['score'] = 5;
			}
			$comments[] = [
				'user_id' => $userId,
				'goods_id' => $k,
				'order_id' => $orderId,
				'images' => $v['img'],
				'content' => $v['content'],
				'score' => $v['score']?:5,
				'create_time' => time(),
				'update_time' => time(),
				'is_anonymous' => 0,
			];
		}
		
		Db::startTrans();
		try {
			
			//更改评价状态
			$orderRes = Db::name('order')->where(['id' => $orderId])->update(['comment_status' => 1]);
			if(!$orderRes) {
				throw new Exception('更改评价状态出错');
			}
			
			//添加商品评价
			$goodsRes = Db::name('goodsComment')->insertAll($comments);
			if(!$goodsRes) {
				throw new Exception('添加评价出错');
			}
			
			if($service_score <0 ) {
				$service_score = 0;
			} else if($service_score > 5) {
				$service_score = 5;
			}
			
			if($shipping_score <0 ) {
				$shipping_score = 0;
			} else if($shipping_score > 5) {
				$shipping_score = 5;
			}
			
			//添加商家评价
			$busRes = Db::name('businessComment')->insert([
				'business_id' => $order['business_id'],
				'order_id' => $orderId,
                'user_id' => $userId,
                'service_score' => $service_score,
                'shipping_score' => $shipping_score,
                'create_time' => time(),
				'update_time' => time(),
			]);
			if(!$busRes) {
				throw new Exception('添加商家详情出错');
			}
			
			Db::commit();
			$this->success('评价成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	
	
    /**
     * 支付宝支付异步处理
     */
    public function notifyAliPay()
    {
        $dir = RUNTIME_PATH.'notify/alipay/';
        $str = "\r\n==========================" . date('Y-m-d H:i:s') . "================================================================\r\n";
        $str .= "处理方式：异步处理 ！.\r\n";
        $data = input('post.');
	    $str .= var_export($data,true) . "\r\n";
        $str .= "==========================================================================================\r\n";
        self::logWrite($str,$dir);
        
        if(!$data)
        {
            self::logWrite('接受参数失败'. "\r\n",$dir);
            echo 'failure';
            die();
        }
        $aop = load_ali();
	    $model = new BatchOrder();
        $pay_no = $data['out_trade_no'];
        
        $row = $model->where(['no' => $pay_no])->find();
        if(!$row) {
	        self::logWrite('数据不存在', $dir);
	        die;
        }
        $payModel = new \app\common\model\Payment();
        $payconfig = $payModel->where(['pay_type' => $payModel::PAY_TYPE_ALI])->find();
        $aop->alipayrsaPublicKey = $payconfig['public_key'];
        if (!$aop->rsaCheckV1($data, NULL,'RSA2'))
        {
            self::logWrite('支付验签失败'. "\r\n",$dir);
            echo 'failure';
            die();
        }
        
        if (isset($data['trade_status']) && $data['trade_status']!='TRADE_SUCCESS' && $data['trade_status']!='TRADE_SUCCESS')
        {
            self::logWrite('交易失败'. "\r\n",$dir);
            echo 'failure';
            die();
        }
	
	    $trade_no = $data['trade_no'];
        $res = $model->paySuccess($pay_no, $trade_no, $model::TYPE_ALI, $data['total_amount']);
        if($res) {
	        self::logWrite("支付成功",$dir);
	        echo 'success';
	        die();
        } else {
        	self::logWrite($model->getError(), $dir);
        	echo $model->getError();
        	die;
        }
    }

    /**
     * 微信支付异步处理
     */
    public function notifyWeChatApp()
    {
        header('Content-type:text/html;charset=utf8');
        $dir = RUNTIME_PATH.'notify/wechat/';
//        $tool = load_tool();
//        $data = $tool::xml2arr(file_get_contents('php://input'));
	    $xml = $GLOBALS['HTTP_RAW_POST_DATA']; //返回的xml
	    //记录日志 支付成功后查看weixin.txt文件是否有内容 如果有xml格式文件说明回调成功
	    $xmlObj=simplexml_load_string($xml,'SimplexmlElement',LIBXML_NOCDATA);
	    $data=json_decode(json_encode($xmlObj),true);
	    
        $str = "\r\n==========================" . date('Y-m-d H:i:s') . "================================================================\r\n";
        $str .= "处理方式：异步处理 ！.\r\n";
        $str .= json_encode($data)."\r\n";
        $str .= "==========================================================================================\r\n";
        self::logWrite($str,$dir);
	
	    $pay_no = $data['out_trade_no'];
	    $model = new BatchOrder();
	    $row = $model->where(['no' => $pay_no])->find();
	    if(!$row) {
		    self::logWrite('数据不存在', $dir);
		    die;
	    }
	    
	    $payModel = new \app\common\model\Payment();
	    $payment = $payModel->where(['pay_type' => $payModel::PAY_TYPE_WEIXIN])->find();
	    //微信支付
	    $config = [
		    'appid' => $payment['appid'],
		    'mch_id' => $payment['mch_id'],
		    'mch_key' => $payment['private_key'],
	    ];
	
	    $wxPay = load_wec("Pay",$config);
	    $sign = $wxPay->checkSign($data);
	
	    // 判断签名是否正确  判断支付状态
	    if ( !$sign || ($data['return_code']!='SUCCESS') || ($data['result_code']!='SUCCESS') ) {
//			echo '验证失败';
		    self::logWrite("签名错误",$dir);
		    die;
	    }
	
	    $trade_no = $data['transaction_id'];
	    $amount = $data['total_fee']/100;
	    $res = $model->paySuccess($pay_no, $trade_no, $model::TYPE_WEIXIN, $amount);
	    if($res) {
		    $xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
		    echo $xml;
		    die();
	    } else {
		    self::logWrite($model->getError(), $dir);
		    die;
	    }
	    
    }
	
	/**
	 * 手动微信支付异步处理
	 */
	public function handWxPay()
	{
		die;
		header('Content-type:text/html;charset=utf8');
		
		$pay_no = input('get.no');
		$model = new BatchOrder();
		$row = $model->where(['no' => $pay_no])->find();
		if(!$row) {
			die('数据不存在');
		}
		
		
		$trade_no = time().time();
		$amount = $row['amount'];
		
		$res = $model->paySuccess($pay_no, $trade_no, $model::TYPE_WEIXIN, $amount);
		if($res) {
			echo 'success';
		} else {
			echo $model->getError();
		}
		
	}

    /**
     * //添加用户影视有限期
     * @param $user //用户资料
     * @param $days //添加天数
     * @return bool
     */
    public function addUserVideoDays($user, $days) {
        $time = $days*24*3600;
        if(!$user['video_time']) {
            $endTime = time() + $time;
        } else {
            $endTime = $user['video_time'] + $time;
        }
        $model = Base::instance("user");
        $res = $model::edit(['uid' =>  $user['uid']],['video_time' => $endTime]);
        if(!$res) {
            return false;
        }
        return true;
    }

    /**
     * //添加用户有限期
     * @param $user //用户资料
     * @param $days //添加天数
     * @return bool
     */
    public function addUserDays($user, $days) {
        $time = $days*24*3600;
        if(!$user['end_time']) {
            $endTime = time() + $time;
        } else {
            $endTime = $user['end_time'] + $time;
        }
        $model = Base::instance("user");
        $res = $model::edit(['uid' =>  $user['uid']],['end_time' => $endTime]);
        if(!$res) {
            return false;
        }
        return true;
    }

    /**
     * 订单商品返利
     * @param $userId
     * @param $orderNo
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function goodsRebate($userId, $orderNo){
        //查看购买的商品
        $goods = Db::table('mall_orders_goods')->alias('og')
            ->join('mall_goods g','og.goodsid = g.goodsid','left')
            ->field('g.*')
            ->where(['og.orderno'=>$orderNo])
            ->select();
        if(!$goods){
            return true;
        }

        $model = Base::instance("user");

        //购买用户信息
        $user = $model::search(['username'=>$userId],['limit'=>1]);
        //如果购买用户有绑定代理商

        //全局规则
        $globalRule = GoodsRebate::search(['id'=>1],['limit'=>1]);

        //给购买用户添加有效天数
        $days = 0;
        $videoDays = 0;
        $aidMoney = $aaidMoney = $aaaidMoney = $pidMoney = $ppidMoney = $pppidMoney = 0;

        foreach($goods as $good){
            $days += $good['add_days'];
            $videoDays += $good['video_days'];

            if($good['rebate_rule'] == 1){
                //返现规则为全局规则

                //如果规则不存在，直接跳过
                if(!$globalRule){
                    continue;
                }

                //有设置返利总金额，以返利总金额计算，否则按售价计算
                if($good['rebate_amount'] > 0){
                    $price = $good['rebate_amount'];
                } else {
                    $price = $good['price'];
                }

                //推荐人返利
                if($globalRule['superior_type'] == 1){
                    //按比例
                    $pidMoney += $price*$globalRule['pid'];
                    $ppidMoney += $price*$globalRule['ppid'];
                    $pppidMoney += $price*$globalRule['pppid'];
                } else {
                    //按固定金额
                    $pidMoney += $globalRule['pid'];
                    $ppidMoney += $globalRule['ppid'];
                    $pppidMoney += $globalRule['pppid'];
                }

                //代理商返利
                if($globalRule['agent_type'] == 1){
                    $aidMoney += $price*$globalRule['aid'];
                    $aaidMoney += $price*$globalRule['aaid'];
                    $aaaidMoney += $price*$globalRule['aaaid'];
                } else{
                    $aidMoney += $globalRule['aid'];
                    $aaidMoney += $globalRule['aaid'];
                    $aaaidMoney += $globalRule['aaaid'];
                }

            }else{
                //返现规则为商品设置的金额
                $pidMoney = $good['user_rebate1'];
                $ppidMoney = $good['user_rebate2'];
                $pppidMoney = $good['user_rebate3'];

                $aidMoney = $good['agent_rebate1'];
                $aaidMoney = $good['agent_rebate2'];
                $aaaidMoney = $good['agent_rebate3'];
            }

        }

        //给用户延长有效期
        if($days > 0){
            $dayRes = self::addUserDays($user, $days);
            if(!$dayRes) {
                throw new Exception('添加有效期出错');
            }
        }

        if($videoDays > 0){
            $dayRes = self::addUserVideoDays($user, $videoDays);
            if(!$dayRes) {
                throw new Exception('添加影视有效期出错');
            }
        }
        if($user['pid'] && $pidMoney > 0){
            $pid = $model::search(['uid' => $user['pid']],['limit'=>1]);
            $moneyRes = $model::setIncEx(['uid' => $user['pid']],'money', $pidMoney);
            if(!$moneyRes){
                return false;
            }
            if(!CapitalLog::addUserMoneyLog($pid,$pidMoney,'订单返现',$orderNo)){
                return false;
            }
        }

        if($user['ppid'] && $ppidMoney > 0){
            $pid = $model::search(['uid' => $user['ppid']],['limit'=>1]);
            $moneyRes = $model::setIncEx(['uid' => $user['ppid']],'money', $ppidMoney);
            if(!$moneyRes){
                return false;
            }
            if(!CapitalLog::addUserMoneyLog($pid,$ppidMoney,'订单返现',$orderNo)){
                return false;
            }
        }

        if($user['pppid'] && $pppidMoney > 0){
            $pid = $model::search(['uid' => $user['pppid']],['limit'=>1]);
            $moneyRes = $model::setIncEx(['uid' => $user['ppppid']],'money', $pppidMoney);
            if(!$moneyRes){
                return false;
            }
            if(!CapitalLog::addUserMoneyLog($pid,$pppidMoney,'订单返现',$orderNo)){
                return false;
            }
        }

        if($user['agent_user_id'] && ($aidMoney > 0 || $aaidMoney > 0 && $aaaidMoney > 0)){
            $agent = UserAgent::search(['user_id' => $user['agent_user_id']],['limit'=>1]);
            $agent1Money = $agent2Money = $agent3Money = 0;
            if($agent['level'] == 3){
                $agent1Money = $aidMoney+$aaidMoney+$aaaidMoney;
            } elseif($agent['level'] == 2){
                $agent1Money = $aidMoney + $aaidMoney;
                $agent2Money = $aaaidMoney;
            } else {
                $agent1Money = $aidMoney;
                $agent2Money = $aaidMoney;
                $agent3Money = $aaaidMoney;
            }
            if($agent1Money > 0){
                $aid = $model::search(['uid' => $user['agent_user_id']],['limit'=>1]);
                $moneyRes = $model::setIncEx(['uid' => $user['agent_user_id']],'money', $agent1Money);
                if(!$moneyRes){
                    return false;
                }
                if(!CapitalLog::addUserMoneyLog($aid,$agent1Money,'代理商订单返现',$orderNo)) {
                    return false;
                }
            }

            if($agent['pid'] && $agent2Money > 0){
                $aid = $model::search(['uid' => $agent['pid']],['limit'=>1]);
                $moneyRes = $model::setIncEx(['uid' => $agent['pid']],'money', $agent2Money);
                if(!$moneyRes){
                    return false;
                }
                if(!CapitalLog::addUserMoneyLog($aid,$agent2Money,'代理商订单返现',$orderNo)) {
                    return false;
                }
            }

            if($agent['ppid'] && $agent3Money > 0){
                $aid = $model::search(['uid' => $agent['ppid']],['limit'=>1]);
                $moneyRes = $model::setIncEx(['uid' => $agent['ppid']],'money', $agent3Money);
                if(!$moneyRes){
                    return false;
                }
                if(!CapitalLog::addUserMoneyLog($aid,$agent3Money,'代理商订单返现',$orderNo)) {
                    return false;
                }
            }
        }

        return true;
    }
	
	/**
	 * 获取支付方式
	 * @param type 支付类型 order订单 recharge充值
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function getPaymentType(){
    	$type = input('post.type');
    	!$type && $this->error('参数错误');
    	
    	$model = new \app\common\model\Payment();
    	if(!in_array($type, $model::$_types)){
    		$this->error('支付类型不存在');
	    }
    	
	    $list = Db::name('payment')
		    ->where('FIND_IN_SET(\''.$type.'\',support_type)')
		    ->where(['status' => 1])
		    ->field('id, name, logo_image, need_password, pay_type')
		    ->select();
	    $this->success('查询成功', $list);
    	
    }
	
	/**
	 * 提醒发货
	 */
    public function orderRemind(){
    	$uid = $this->auth->id;
    	$orderId = input('post.order_id');
    	!$orderId && $this->error('参数错误');
    	
    	$model = new \app\common\model\Order();
    	$order = $model->find($orderId);
    	!$order && $this->error('订单不存在');
    	
    	if($order['order_status'] != $model::STATUS_WAIT_DELIVERY) {
    		$this->error('非待发货订单');
	    }
    	
    	$model = new OrderRemind();
    	$res = $model->isUpdate(false)->save([
    	    'user_id' => $uid,
		    'order_id' => $orderId,
		    'business_id' => $order['business_id'],
	    ]);
    	
    	if($res) {
    		$this->success('提醒成功');
	    } else {
    		$this->error('操作出错，请稍候重试');
	    }
    }
	
	
	/**
	 * 报销订单
	 */
    public function reimburseOrder(){
        $orderId = $this->request->post('order_id');
        if(!$orderId) {
        	$this->error('参数错误');
        }
        
        $userId = $this->auth->id;
        $order = Db::name('order')
	        ->where(['user_id'=> $userId, 'id' => $orderId])
	        ->find();
        if(!$order) {
        	$this->error('订单不存在');
        }
        
        if($order['reimburse_status'] != \app\common\model\Order::REIMBURSE_STATUS_N) {
        	$this->error('你已经申请过了');
        }
        
        if($order['order_status'] != \app\common\model\Order::STATUS_SIGN) {
        	$this->error('未完成订单不可申请报销');
        }
        $model = new ReimburseRecord();
        $res = $model->addRecord($order);
        if($res) {
        	$this->success('申请成功，等待审核');
        } else {
        	$this->error($model->getError());
        }
    }
    
}
